#!/bin/bash

# 设置脚本在遇到错误时立即退出
set -e

# 绑定变量值
ASSEMBLY_MESSAGE="${assembly.message}"

# 容器名称
CONTAINER_NAME="${project.build.finalName}"
# 镜像名称
IMAGE_NAME="${project.build.finalName}:last"
# 暴漏端口
CONTAINER_PORT="${server.port}"

# 输出消息
echo "${ASSEMBLY_MESSAGE}"


tips() {
	echo ""
	echo "Tips, please use command: sh docker.sh [start|stop|restart|build]. For example: sh docker.sh start"
	echo ""
	exit 1
}

stop() {
    echo "Stopping running container..."
    docker stop "${CONTAINER_NAME}"
    echo "Removing stopped container..."
    docker rm -f "${CONTAINER_NAME}"
}

start() {

    #编译镜像
    build

    # 使用docker ps命令查找容器是否存在
    if docker ps -a --format '{{.Names}}' | grep -q "$CONTAINER_NAME"; then
        echo "容器已存在,请先停止容器..."
        #restart
    else
        echo "容器不存在..."
        new
    fi

}


restart(){
    stop
    start
}


build(){
  echo "Building new image..."
  docker build -t "${IMAGE_NAME}" .
  echo "Building success..."
}


new(){
  echo "Starting new container..."
  docker run -d --name "${CONTAINER_NAME}" \
      --cap-add=SYS_PTRACE \
      -p ${CONTAINER_PORT}:${CONTAINER_PORT} \
      -v "$(pwd)/dumps:/app/dumps" \
      -v "$(pwd)/logs:/app/logs" \
      "${IMAGE_NAME}"

  echo "Container has been restarted."
}


# 根据输入参数执行对应方法，不输入则执行tips提示方法
case "$1" in
   "start")
     start
     ;;
   "stop")
     stop
     ;;
   "build")
     status
     ;;
   "restart")
     restart
     ;;
   *)
     tips
     ;;


esac
